package cn.monkey.transport.core;

import java.util.Arrays;

public final class CombinedExchangeFactory<C, EXCHANGE extends Exchange> implements ExchangeFactory<C, EXCHANGE> {

    private final ExchangeFactory<C, EXCHANGE> factory;

    @SafeVarargs
    public CombinedExchangeFactory(ExchangeFactory<C, EXCHANGE>... factories) {
        this.factory = Arrays.stream(factories)
                .reduce((f1, f2) -> (key, exchange, c) -> f2.apply(key, f1.apply(key, exchange, c), c))
                .orElseThrow();
    }

    @Override
    public EXCHANGE apply(String key, Exchange exchange, C c) {
        return this.factory.apply(key, exchange, c);
    }
}
